<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function MyPromise(executor) {
            this.status = 'pending'; // 状态
            this.value = undefined;  // 成功的值
            this.reason = undefined; // 失败的原因
            this.onFulfilledCallbacks = []; // 成功的回调函数
            this.onRejectedCallbacks = []; // 失败的回调函数

            const resolve = (value) => {
                if (this.status === 'pending') {
                    this.status = 'fulfilled';
                    this.value = value;
                    this.onFulfilledCallbacks.forEach(fn => fn());
                }
            }

            const reject = (reason) => {
                if (this.status === 'pending') {
                    this.status = 'rejected';
                    this.reason = reason;
                    this.onRejectedCallbacks.forEach(fn => fn());
                }
            }

            try {
                executor(resolve, reject);
            } catch (error) {
                reject(error);
            }
        }

        MyPromise.prototype.then = function (onFulfilled, onRejected) {
            if (this.status === 'fulfilled') {
                onFulfilled(this.value);
            }
            if (this.status === 'rejected') {
                onRejected(this.reason);
            }
            if (this.status === 'pending') {
                this.onFulfilledCallbacks.push(() => {
                    onFulfilled(this.value);
                });
                this.onRejectedCallbacks.push(() => {
                    onRejected(this.reason);
                });
            }
        }

        const p1 = new MyPromise((resolve, reject) => {
            setTimeout(() => {
                resolve('成功');
            }, 1000);
        });
        const p2 = new MyPromise((resolve, reject) => {
            setTimeout(() => {
                reject('失败');
            }, 1000);
        });
        p1.then((res) => {
            console.log(res);
        }).catch((err) => {
            console.log(err);
        })
        p2.then((res) => {
            console.log(res);
        }).catch((err) => {
            console.log(err);
        })
    </script>
</body>
</html>